﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BFlatCompile.Nodes
{
	public class MethodParam : ICodeContainer
	{
		public string Name { get; private set; }
		public int NameIndex { get { return Variable.Table.GetId(this.Name); } }
		public Expression Value { get; private set; }

		private static int idAlloc = 1;

		private int id = 0;
		public int ID
		{
			get
			{
				if (this.id == 0 && this.Value != null)
				{
					this.id = idAlloc++;
				}
				return this.id;
			}
		}
		public Token Token { get; private set; }
		public MethodParam(string name, Expression defaultValue, Token token)
		{
			Variable.Table.Register(name);
			this.Name = name;
			this.Value = defaultValue;
			this.Token = token;
		}

		public static MethodParam Parse(Tokens tokens)
		{
			string name = tokens.PopIdentifier();
			Token nameToken = tokens.PreviousToken();

			Expression defaultValue = null;
			if (tokens.PopIfPresent("="))
			{
				defaultValue = Expression.Parse(tokens);
			}

			return new MethodParam(name, defaultValue, nameToken);
		}

		public static MethodParam[] ParseList(Tokens tokens)
		{
			List<MethodParam> list = new List<MethodParam>();
			while (tokens.Peek() != ")")
			{
				if (list.Count > 0)
				{
					tokens.PopExpected(",");
				}

				list.Add(Parse(tokens));
			}

			return list.ToArray();
		}

		public void ResolveCode(Class c, Dictionary<object, object> parents)
		{
			if (this.Value != null)
			{
				this.Value.ResolveCode(c, parents);
			}
		}

		public void ResolveClassToThis(Class c)
		{
			if (this.Value != null)
			{
				this.Value.ResolveClassToThis(c);
			}
		}
	}
}
